"""OCR 识别服务模块"""
import base64
import json
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.ocr.v20181119 import ocr_client, models

from common.tools.remove_symbol import remove_symbol


class OCRService:
    """OCR 识别服务类"""
    
    @staticmethod
    def image_to_base64(image_path):
        """将图片转换为 base64"""
        with open(image_path, "rb") as image_file:
            return base64.b64encode(image_file.read()).decode('utf-8')
    
    @staticmethod
    def recognize(tx_secret_id, tx_secret_key, address, img_path, choose='question'):
        """
        识别图片中的文字
        
        Args:
            tx_secret_id: 腾讯云 Secret ID
            tx_secret_key: 腾讯云 Secret Key
            address: 腾讯云地域
            img_path: 图片路径
            choose: 识别类型 'question' 或 'option'
        
        Returns:
            识别出的文字内容
        """
        try:
            # 创建腾讯云 OCR 客户端
            cred = credential.Credential(tx_secret_id, tx_secret_key)
            
            httpProfile = HttpProfile()
            httpProfile.endpoint = "ocr.tencentcloudapi.com"
            clientProfile = ClientProfile()
            clientProfile.httpProfile = httpProfile
            client = ocr_client.OcrClient(cred, address, clientProfile)
            
            # 创建请求
            req = models.GeneralBasicOCRRequest()
            params = {
                "ImageBase64": OCRService.image_to_base64(img_path)
            }
            req.from_json_string(json.dumps(params))
            
            # 发送请求
            resp = client.GeneralBasicOCR(req)
            
            # 处理响应
            content = ''
            if choose == 'question':
                # 题目识别：直接拼接所有文字
                for item in resp.TextDetections:
                    content += item.DetectedText
            elif choose == 'option':
                # 选项识别：去除 A/B/C/D 标记
                content += '选项：['
                processed_texts = []
                for item in resp.TextDetections:
                    clean_text = remove_symbol(item.DetectedText)
                    clean_text = clean_text.replace('A', '').replace('B', '').replace('C', '').replace('D', '')
                    processed_texts.append(clean_text)
                content += ' '.join(processed_texts) + ']'
            
            return content
            
        except TencentCloudSDKException as err:
            print('│ 腾讯OCR报错：\n', err)
            return None
